package com.example.score.score;

import cn.hutool.core.bean.BeanUtil;
import com.example.score.entity.Message;
import com.example.score.entity.SportData;
import com.example.score.entity.Sportsman;
import com.example.score.utils.JsonSocketMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Collections;

@Slf4j
@Service
public class ConfirmSocket extends TextWebSocketHandler {

    private WebSocketSession hyperReferee;


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        hyperReferee = session;
        hyperReferee.sendMessage(JsonSocketMessageUtil.wrapMessage("success"));
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        Message data = JsonSocketMessageUtil.parseMessageToJson(message);
        // 利用反射动态调用方法
        Method method = this.getClass().getDeclaredMethod(data.getAction(), WebSocketSession.class, Message.class);
        method.invoke(this, session, data);
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        hyperReferee = null;
    }

    public void submitScore(Sportsman sportsman, String taskId) {
        if (hyperReferee != null) {
            SportData data = BeanUtil.copyProperties(sportsman, SportData.class);
            data.setTaskId(taskId);
            try {
                hyperReferee.sendMessage(JsonSocketMessageUtil.wrapMessage(new Message("confirm", Collections.singletonList(data))));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
